<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Template
{
    function  __construct()
    {
        $this->CI =& get_instance();
    }

    function build($view, $data = '', $header = '', $footer = '', $template = '')
    {
        if($template == '' || !is_dir('system/application/views/templates/'.$template))
        {
            $template = $this->CI->config->item('site_template');
        }

        $tpl['header'] = 'templates/'.$template.'/header';
        $tpl['footer'] = 'templates/'.$template.'/footer';
        
        if(!isset($header['title']))
        {
            $header['title'] = $this->CI->config->item('site_default_title');
        }

        if(!isset($header['js']))
        {
            $header['javascript'] = '';
        }
        else
        {
            $header['javascript'] = '';
            $jsArray = $header['js'];
            for($i=0;$i<count($jsArray);$i++)
            {
                $header['javascript'] .= $this->parse_js($jsArray[$i]);
            }
        }

        if(!isset($header['css']))
        {
            $header['css_string'] = '';
        }
        else
        {
            $header['css_string'] = '';
            $cssArray=$header['css'];
            for($i=0;$i<count($cssArray);$i++)
            {
                $header['css_string'] .= $this->parse_css($cssArray[$i]);
            }
        }

        $this->CI->load->view($tpl['header'], $header);
        $this->CI->load->view($view, $data);
        $this->CI->load->view($tpl['footer'], $footer);
    }

	function parse_js($src)
    {
        # If $src is a complete URL, don't include the base_js_url() function
        if(substr($src, 0, 4) == 'http')
        {
            $result = '<script type="text/javascript" src="'.$src.'"></script>
            ';
        }
        else
        {
            $result = '<script type="text/javascript" src="'.base_js_url().$src.'"></script>
            ';
        }
        return $result;
    }

    function parse_css($src)
    {
        # If $src is a complete URL, don't include the base_css_url() function
        if(substr($src, 0, 4) == 'http')
        {
            $result = '<link rel="stylesheet" href="'.$src.'" type="text/css" media="screen" />
            ';
        }
        else
        {
            $result = '<link rel="stylesheet" href="'.base_css_url().$src.'" type="text/css" media="screen" />
            ';
        }
        return $result;
    }
}

?>